package com.stress.testing.agent;

import com.stress.testing.agent.resolver.AgentResourceResolver;
import com.stress.testing.agent.resolver.DefaultAgentResourceResolver;

import java.io.File;
import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.net.URL;
import java.util.List;
import java.util.jar.JarFile;

public class Bootstrap {
    private static Logger logger = Logger.getLogger(Bootstrap.class);

    public static void premain(String agentArgs, Instrumentation inst) {
        logger.info("agent开始运行...");

        // 解析jar包资源
        AgentResourceResolver agentResourceResolver = new DefaultAgentResourceResolver();
        agentResourceResolver.resolve();

        // 将必要包添加到ClassLoaderSearch
        // ** 没有解决bytebuddy的问题，jar都打进agent里，这里不需要了
//        appendToClassLoaderSearch(inst, agentResourceResolver.getAgentDependenceURL());

        // 当外部jar中的类写在这里时，启动就会加载，导致异常
        // 神奇的是，写到其他类中，启动时则不会加载
        new AgentStarter(inst, agentResourceResolver).start();
    }

    private static void appendToClassLoaderSearch(Instrumentation inst, List<URL> agentDependenceURL) {
        if (agentDependenceURL == null || agentDependenceURL.size() <= 0) {
            return;
        }

        for (URL url : agentDependenceURL) {

            JarFile jarFile = null;
            try {
                jarFile = new JarFile(new File(url.getFile()));
            } catch (IOException e) {
                logger.error("JarFile创建失败:" + url.getFile(), e);
                continue;
            }

            inst.appendToBootstrapClassLoaderSearch(jarFile);
        }
    }
}
